package br.skytef.stmanager.daos;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.skytef.stmanager.entities.ContatoEntity;
import br.skytef.stmanager.utils.Pool;

public class ContatoDao {
	/**
	 * Variável para conexão, obtido através de um Pool(br.skytef.stmanager.utils.Pool)
	 */
	private static Connection conexao = null;	
	/**
	 * Inserir nova contato
	 * @param contato
	 */

	public void inserir(ContatoEntity contato){
		try {
			conexao = Pool.getConnection();
			String query = "INSERT INTO contato (nome,telefone,email,data_inclusao)"
					+ "VALUES (?,?,?,?);";
			PreparedStatement preparedStmt = conexao.prepareStatement(query);
			preparedStmt.setString				(1,contato.getNome());
			preparedStmt.setString				(2,contato.getTelefone());
			preparedStmt.setString				(3,contato.getEmail());
			preparedStmt.setTimestamp		    (4,contato.getDataInclusao());
			preparedStmt.execute();	
			conexao.close();

		} catch (SQLException e) {
			System.out.println("SQL erro: "+ e);
		}catch (ClassCastException e) {
			System.out.println("Classe erro: "+ e);
		} catch (Exception e) {
			System.out.println("Geral erro: "+ e);
		}

	}

	public ContatoEntity bucarContato (String username)
	{
		ContatoEntity contato = null;
		try {

			conexao = Pool.getConnection();
			Statement st = conexao.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM contato WHERE nome = '"+ username +"' ORDER BY nome;");
			if (rs.next()) {
				do {                      
					contato = new ContatoEntity();
					contato.setContatoId(rs.getInt("id"));
					contato.setNome(rs.getString("nome"));
					contato.setTelefone(rs.getString("telefone"));
					contato.setEmail(rs.getString("email"));
				} while (rs.next());
			}
			conexao.close();			
		}catch (SQLException e) {
			System.out.println("SQL erro: "+ e);
		}
		return contato;
	}
	
	public List <ContatoEntity> listar(int idContato){
		List <ContatoEntity> contatos = null;
		ContatoEntity contato;
		try {
			conexao = Pool.getConnection();
			Statement st = conexao.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM contato WHERE id  = '"+ idContato  +"' ORDER BY nome;");
			if (rs.next()) {   
				contatos = new ArrayList<ContatoEntity>();
				do {                      
					contato = new ContatoEntity();
					contato.setContatoId((rs.getInt("contatoId")));
					contato.setNome((rs.getString("nome")));
					contatos.add(contato);  
				} while (rs.next());
			}
			conexao.close();
		} catch (SQLException e) {
			System.out.println("SQL erro: "+ e);
		} catch (Exception e) {
			System.out.println("Geral erro: "+ e);
		}
		return contatos;		
	}


}
